package com.gitee.gen.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gitee.gen.common.Action;
import com.gitee.gen.common.GeneratorParam;
import com.gitee.gen.common.Result;
import com.gitee.gen.entity.DatasourceConfig;
import com.gitee.gen.gen.CodeFile;
import com.gitee.gen.gen.GeneratorConfig;
import com.gitee.gen.service.DatasourceConfigService;
import com.gitee.gen.service.GeneratorService;

/**
 * @author tanghc
 */
@RestController
@RequestMapping("generate")
public class GeneratorController {

    @Autowired
    private DatasourceConfigService datasourceConfigService;

    @Autowired
    private GeneratorService generatorService;

    /**
     * 生成代码
     *
     * @param generatorParam 生成参数
     * @return 返回代码内容
     */
    @RequestMapping("/code")
    public Result code(@RequestBody GeneratorParam generatorParam) {
        int datasourceConfigId = generatorParam.getDatasourceConfigId();
        DatasourceConfig datasourceConfig = datasourceConfigService.getById(datasourceConfigId);
        GeneratorConfig generatorConfig = GeneratorConfig.build(datasourceConfig);
        List<CodeFile> generate = generatorService.generate(generatorParam, generatorConfig);

        for (CodeFile codeFile : generate) {
            String content = codeFile.getContent();
            if (StringUtils.isBlank(content)) {
                continue;
            }

            String moduleName = "";
            // 动态生成所属模块名称
            switch (codeFile.getLayer()) {
                case "dal":
                    moduleName = generatorParam.getDalModuleName();
                    break;
                case "service":
                    moduleName = generatorParam.getServiceModuleName();
                    break;
                case "controller":
                    moduleName = generatorParam.getControllerModuleName();
                    break;
                default:
                    break;
            }
            if (StringUtils.isBlank(moduleName)) {
                return Action.err("文件生成所需模块参数为空");
            }
            // dal层地址
            String dalPath = generatorParam.getDalModuleName().replace("-", "");
            // service层地址
            String servicePath = generatorParam.getServiceModuleName().replace("-", "");
            // controller层地址
            String controllerPath = generatorParam.getControllerModuleName().replace("-", "");
            // 模块地址
            String modulePath = moduleName.replace("-", "");
            // 包名地址
            String packagePath = generatorParam.getPackageName().replace(".", "/");
            // 文件最终生成地址
            String generatePath = codeFile.getGeneratePath().replace("${moduleName}", moduleName)
                .replace("${packagePath}", packagePath).replace("${modulePath}", modulePath);
            String filePath = generatorParam.getGenerateLocalPath() + "/" + generatePath;

            // 替换文件中的自定义包名通配符
            content = content.replace("${dalPath}", dalPath).replace("${servicePath}", servicePath)
                .replace("${controllerPath}", controllerPath).replace("${modulePath}", modulePath);
            // 如果是cyt项目则使用工具包的page、beanutils
            String commonPackage =
                generatorParam.getPackageName() + "." + moduleName.substring(0, moduleName.indexOf("-"));
            String cytPage = generatorParam.getPackageName().contains("cyt")
                ? "import com.cyt.chanseyx.common.bean.Page;" : "import " + commonPackage + "common.bean.Page;";
            String cytResult = generatorParam.getPackageName().contains("cyt")
                ? "import com.cyt.chanseyx.common.bean.Result;" : "import " + commonPackage + "common.bean.Result;";
            String cytBeanUtil =
                generatorParam.getPackageName().contains("cyt") ? "import com.cyt.chanseyx.common.utils.BeanUtils;"
                    : "import " + commonPackage + "common.utils.BeanUtils;";
            String cytQueryBase =
                generatorParam.getPackageName().contains("cyt") ? "import com.cyt.chanseyx.common.bean.QueryBase"
                    : "import " + commonPackage + "common.bean.QueryBase;";
            content = content.replace("${cytPage}", cytPage).replace("${cytResult}", cytResult)
                .replace("${cytBeanUtil}", cytBeanUtil).replace("${cytQueryBase}", cytQueryBase);

            codeFile.setContent(content);
            if (StringUtils.isEmpty(filePath) || StringUtils.isBlank(generatorParam.getGenerateLocalPath())) {
                continue;
            }

            StringBuilder stringBuilder = new StringBuilder(filePath);
            stringBuilder.append(File.separator).append(codeFile.getFileName());
            File file = new File(stringBuilder.toString());
            if (file.exists()) {
                file.delete();
            }
            try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
                FileCopyUtils.copy(content.getBytes(StandardCharsets.UTF_8), fileOutputStream);
            } catch (Exception e) {
                e.printStackTrace();
                return Action.err(filePath + " 文件生成路径不存在,请检查生成代码参数");
            }
        }

        return Action.ok(generate);
    }
}
